package com.mysite.examination.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

public class LoginInterceptor extends HandlerInterceptorAdapter {

	protected Logger logger = Logger.getLogger(this.getClass());
	private static final String X_REQUESTED_WITH = "X-Requested-With";

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		String contextPath = request.getContextPath();
		String uri = request.getRequestURI();
		logger.info("contextPath: " + contextPath + " \t uri: " + uri);
		
		HttpSession session = request.getSession();

		// 用户登录认证
		if (session.getAttribute("CURRENT_USER") == null) {// 登录超时或没有登录
			if (request.getHeader(X_REQUESTED_WITH) != null || request.getParameter(X_REQUESTED_WITH) != null) {// 异步请求
				response.setStatus(301);
				PrintWriter out = response.getWriter();
				out.write("登录超时；请重新登录！");
				out.flush();
				out.close();
			} else {// 同步请求
				response.sendRedirect(contextPath + "/api/login");
			}
			return false;
		}

		return true;
	}
}
